import { ref } from 'vue';
import { defineStore } from 'pinia';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
import api from '@/http/api';
import { useCache } from "@/utils/cache";
import tool from "@/utils/tool";

const { wsCache } = useCache();

export const useUserStore = defineStore('user', () => {
  const loadingInstance = ref(null);
  const loading = ref(false);

  const userInfo = ref({
    id: '',
    name: '',
    organizations: [],
  });

  const userData = ref({});
  const orgData = ref({});
  const dateData = ref({});

  const setToken = (val) => {
    wsCache.set('user.token', val);
  };

  const getToken = () => {
    return wsCache.get('user.token') || '';
  };

  const setUser = (data) => {
    userInfo.value = data.user;
    userData.value = data.userData;
    orgData.value = data.orgData;
    dateData.value = data.dateData;
    setToken(data.token)
  };

  const getUser = () => {
    return userInfo.value;
  };

  const getUserData = () => {
    return userData.value;
  };

  const getOrgData = () => {
    return orgData.value;
  };

  const initUserInfo = async() => {
    if (getToken() === '') {
      return null;
    }

    if (userInfo.value && userInfo.value.id) {
      return userInfo.value;
    }

    if (loading.value) {
      await sleep(100);
      return await initUserInfo();
    }

    loading.value = true;
    const res = await api.post('/business/user');
    if (res.code === '1') {
      loading.value = false;
      setUser(res.data);
      return userInfo.value;
    } else {
      loading.value = false;
      setToken(null);
      throw new Error('用户信息获取失败！');
    }
  };

  const isLogin = () => {
    return new Promise((resolve, reject) => {
      if (getToken() === '') {
        resolve(false);
        return;
      }

      api.post('/business/user').then(res => {
        if (res.code === '1') {
          resolve(res.data);
        } else {
          reject();
        }
      }).catch(() => {
        reject();
      });
    });
  };

  const login = async(loginInfo) => {
    loadingInstance.value = ElLoading.service({
      fullscreen: true,
      text: '登录中，请稍候...',
    });
    try {
      const res = await api.login(loginInfo);
      if (res.code === '1') {
        setUser(res.data);
        window.location.href = tool.getBaseUrl() + "/choose.html";
      } else {
        ElMessage.error(res.message);
      }
    } catch (e) {
      console.log(e);
      loadingInstance.value.close();
    }
    loadingInstance.value.close();
  };

  const logout = async() => {
    ElMessageBox.confirm("请确认是否退出登录？", "提示", { type: "warning" }).then(() => {
      api.logout().then(async (res) => {
        ElMessage.success(res.message);
        clearStorage();
        window.location.href = tool.getBaseUrl() + '/';
      });
    }).catch(() => {});
  };

  const parseSymbol = async(symbol) => {
    if (!symbol || typeof symbol !== "string") return symbol;
    if (!symbol || symbol.trim().length === 0) return null;
    if (!symbol.trim().startsWith("${")) return symbol;

    let tplValue = symbol.trim().substring(2, symbol.trim().length - 1);
    let tplValues = tplValue.split(".");
    if (tplValues.length < 2) return symbol;

    switch (tplValues[0]) {
      case "user":
        return userData.value[tplValues[1]];
      case "org":
        return orgData.value[tplValues[1]];
      case "script":
        return await api.runScript(tplValues[1]);
      case "date":
        if (tplValues[1] === 'currTime') {
          return new Date().getTime();
        } else if (dateData.value && dateData.value[tplValues[1]]) {
          return dateData.value[tplValues[1]];
        } else if (tplValues[1] === 'currYear') {
          return new Date().getFullYear();
        } else if (tplValues[1] === 'currMonth') {
          return new Date().getMonth() + 1;
        } else if (tplValues[1] === 'currDay') {
          return new Date().getDate();
        } else if (tplValues[1] === 'currDate') {
          const date = new Date();
          const year = date.getFullYear();
          const month = date.getMonth() + 1;
          const day = date.getDate();
          return year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
        } else if (tplValues[1] === 'currMonthFirst') {
          const date = new Date();
          const year = date.getFullYear();
          const month = date.getMonth() + 1;
          return year + '-' + (month < 10 ? '0' : '') + month + '-01';
        } else if (tplValues[1] === 'first7Day') {
          const date = new Date();
          date.setDate(date.getDate() - 7 + 1)
          const year = date.getFullYear();
          const month = date.getMonth() + 1;
          const day = date.getDate();
          return year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
        } else if (tplValues[1] === 'first30Day') {
          const date = new Date();
          date.setDate(date.getDate() - 30 + 1)
          const year = date.getFullYear();
          const month = date.getMonth() + 1;
          const day = date.getDate();
          return year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
        }
    }
    return null;
  };

  const sleep = async (d) => {
    return new Promise((resolve) => setTimeout(resolve, d))
  };

  const clearStorage = () => {
    wsCache.delete('user.token')
    window.sessionStorage.clear();
  };

  return {
    setUser,
    getUser,
    getUserData,
    getOrgData,
    setToken,
    getToken,
    login,
    logout,
    initUserInfo,
    isLogin,
    loadingInstance,
    clearStorage,
    parseSymbol
  };
});
